<?php

use Illuminate\Support\Arr;

if (!function_exists('config_path')) {
    /**
     * Get the configuration path.
     * @param string $path
     * @return string
     */
    function config_path($path = '')
    {
        return app()->basePath() . '/config' . ($path ? '/' . $path : $path);
    }
}
if (!function_exists('public_path')) {
    function public_path($path = '')
    {
        $nowPath = app()->basePath() . '/public' . ($path ? '/' . $path : $path);
        $path = str_replace('\\', '/', $nowPath);
        return realpath(str_replace('//', '/', $path));
    }
}
if (!function_exists("array_column")) {

    function array_column($array, $column_name)
    {
        return array_map(function ($element) use ($column_name) {
            return $element[$column_name];
        }, $array);
    }
}
function getRateDay()
{
    $startday = date('Y-m-01');
    $startday = strtotime($startday); //该月第一天
    $oneday = date('Y-m-d'); //下订单的这一天
    $oneday = strtotime($oneday);
    $endday = date('Y-m-t'); //该月最后一天
    $endday = strtotime($endday);
    $other = $endday - $oneday;
    $totals = $endday - $startday;
    $totals = ($totals / 86400) + 1;
    $other = ($other / 86400) + 1;
    return $other / $totals;
}

function DateAdd($part, $n, $date)
{
    switch ($part) {
        case "y":
            $val = date("Y-m-d H:i:s", strtotime($date . " +$n year"));
            break;
        case "m":
            $val = date("Y-m-d H:i:s", strtotime($date . " +$n month"));
            break;
        case "w":
            $val = date("Y-m-d H:i:s", strtotime($date . " +$n week"));
            break;
        case "d":
            $val = date("Y-m-d H:i:s", strtotime($date . " +$n day"));
            break;
        case "h":
            $val = date("Y-m-d H:i:s", strtotime($date . " +$n hour"));
            break;
        case "n":
            $val = date("Y-m-d H:i:s", strtotime($date . " +$n minute"));
            break;
        case "s":
            $val = date("Y-m-d H:i:s", strtotime($date . " +$n second"));
            break;
    }
    return $val;
}

//xml转化为数组
function parseNamespaceXml($xmlstr)
{
    if (strlen($xmlstr) < 10) {
        $xmlstr = "<root>";
        $xmlstr .= "<IRESULT>-1</IRESULT>";
        $xmlstr .= "</root>";
    }
    $xmlstr = preg_replace('/\sxmlns="(.*?)"/', ' _xmlns="${1}"', $xmlstr);
    $xmlstr = preg_replace('/<(\/)?(\w+):(\w+)/', '<${1}${2}_${3}', $xmlstr);
    $xmlstr = preg_replace('/(\w+):(\w+)="(.*?)"/', '${1}_${2}="${3}"', $xmlstr);
    $xmlobj = simplexml_load_string($xmlstr);
    return json_decode(json_encode($xmlobj), true);
}

function createNonceStr($length = 16)
{
    $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
    //$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    $str = "";
    for ($i = 0; $i < $length; $i++) {
        $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
    }
    return $str;
}

function xml_to_data($xml)
{
    $values = array();
    if ($xml) {
        libxml_disable_entity_loader(true); //将XML转为array//禁止引用外部xml实体
        $values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    }
    return $values;
}

function data_to_xml($params)
{
    if (!is_array($params) || count($params) <= 0) {
        return false;
    }
    $xml = "<xml>";
    foreach ($params as $key => $val) {
        if (is_numeric($val)) {
            $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
        } else {
            $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
        }
    }
    $xml .= "</xml>";
    return $xml;
}

function ToUrlParams($params)
{
    $string = '';
    ksort($params);
    if (!empty($params)) {
        $array = array();
        foreach ($params as $key => $value) {
            $array[] = $key . '=' . $value;
        }
        $string = implode("&", $array);
    }
    return $string;
}

/**
 * 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
 * @param $para 需要拼接的数组
 * return 拼接完成以后的字符串
 */
function createLinkstring($para)
{
    $arg = "";
    while (list($key, $val) = each($para)) {
        $arg .= $key . "=" . $val . "&";
    }
    //去掉最后一个&字符
    $arg = substr($arg, 0, count($arg) - 2);

    //如果存在转义字符，那么去掉转义
    if (get_magic_quotes_gpc()) {
        $arg = stripslashes($arg);
    }

    return $arg;
}

/**
 * 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串，并对字符串做urlencode编码
 * @param $para 需要拼接的数组
 * return 拼接完成以后的字符串
 */
function createLinkstringUrlencode($para)
{
    $arg = "";
    while (list($key, $val) = each($para)) {
        $arg .= $key . "=" . urlencode($val) . "&";
    }
    //去掉最后一个&字符
    $arg = substr($arg, 0, count($arg) - 2);

    //如果存在转义字符，那么去掉转义
    if (get_magic_quotes_gpc()) {
        $arg = stripslashes($arg);
    }

    return $arg;
}

function rsaSign($data, $private_key)
{
    //以下为了初始化私钥，保证在您填写私钥时不管是带格式还是不带格式都可以通过验证。
    $private_key = str_replace("-----BEGIN RSA PRIVATE KEY-----", "", $private_key);
    $private_key = str_replace("-----END RSA PRIVATE KEY-----", "", $private_key);
    $private_key = str_replace("\n", "", $private_key);

    $private_key = "-----BEGIN RSA PRIVATE KEY-----" . PHP_EOL . wordwrap($private_key, 64, "\n", true) . PHP_EOL . "-----END RSA PRIVATE KEY-----";

    $res = openssl_get_privatekey($private_key);

    if ($res) {
        openssl_sign($data, $sign, $res);
    } else {
        logResult2("您的私钥格式不正确!" . "<br/>" . "The format of your private_key is incorrect!");
        exit();
    }
    openssl_free_key($res);
    //base64编码
    $sign = base64_encode($sign);
    return $sign;
}

/** 兼容key没有双引括起来的JSON字符串解析
 * @param String $str JSON字符串
 * @param boolean $mod true:Array,false:Object
 * @return Array/Object
 */
function ext_jsonstr($str)
{
    if (preg_match('/\w:/', $str)) $str = preg_replace('/(\w+):/is', '"$1":', $str);
    if (preg_match('/:0\w/', $str)) $str = preg_replace('/:(\w+)/is', ':"$1"', $str);
    return $str;
}

// 得到request参数
function getRequestParams($request, $key_array)
{
    $data = null;
    foreach ($key_array as $key) {
        if (gettype($request[$key]) != NULL && $request[$key] != '') {
            $data[$key] = $request[$key];
        }
    }
    return $data;
}

function WriteLog($content)
{
    $fp_tmp = fopen("/tmp/" . date("Y-m-d") . ".txt", "a+");
    fputs($fp_tmp, $content . "\t" . date("Y-m-d H:i:s") . "\n");
    fclose($fp_tmp);
}

function strToHex($string)
{
    $hex = '';
    for ($i = 0; $i < strlen($string); $i++) {
        $hex .= dechex(ord($string[$i]));
    }
    return $hex;
}

function hexToStr($hex)
{
    $string = '';
    for ($i = 0; $i < strlen($hex) - 1; $i += 2) {
        $string .= chr(hexdec($hex[$i] . $hex[$i + 1]));
    }
    return $string;
}

function getBytes($string)
{
    $bytes = array();
    for ($i = 0; $i < strlen($string); $i++) {
        $bytes[] = ord($string[$i]);
    }
    return $bytes;
}

function toStr($bytes)
{
    $str = '';
    foreach ($bytes as $ch) {
        $str .= chr($ch);
    }
    return $str;
}

function get_millisecond()
{
    list($usec, $sec) = explode(" ", microtime());
    $msec = round($usec * 1000);
    return str_pad($msec, 3, '0', STR_PAD_RIGHT);
}

///address=>[lng] => 113.68827141439 [lat] => 34.779807706414
function getLatLong($address, $ak = '87c3e9435d10e6ad8a06622506836849')
{
    $location = null;
    if (!$address) return $location;
    $url = "http://api.map.baidu.com/geocoder/v2/?output=json&ak=$ak&address=" . $address;
    $response = get_url_content($url);
    $response = json_decode($response);
    if (!$response) return $location;
    if ($response->status == 0)
        $location = $response->result->location;
    return $location;
}

//[lng] => 113.68827141439 [lat] => 34.779807706414 ==>address
function getLocation($lng, $lat, $ak = '87c3e9435d10e6ad8a06622506836849')
{
    $address = "";
    if ($lng < 100) return "";
    $url = "http://api.map.baidu.com/geocoder/v2/?ak=$ak&output=json&location=$lat,$lng";
    $response = get_url_content($url);
    $response = json_decode($response);
    if (!$response) return $address;
    if ($response->status == 0) {
        $province = $response->result->addressComponent->province;
        $city = $response->result->addressComponent->city;
        $district = $response->result->addressComponent->district;
        $sematic_description = $response->result->sematic_description;
        if ($sematic_description)
            $address = $province . $city . $district . $sematic_description;
        else
            $address = $response->result->formatted_address;
    }
    return $address;
}

//使用原始库 优点 控制时间 不受环境影响比如发短信提交后就直接结束
function make_request($url, $params, $type = 'GET')
{
    foreach ($params as $key => &$val) {
        if (is_array($val)) $val = implode(',', $val);
        $post_params[] = $key . '=' . urlencode($val);
    }
    $post_string = implode('&', $post_params);
    $parts = parse_url($url);
    $fp = fsockopen($parts['host'], isset($parts['port']) ? $parts['port'] : 80, $errno, $errstr, 30);
    if ('GET' == $type) $parts['path'] .= '?' . $post_string;
    $out = "$type " . $parts['path'] . " HTTP/1.1\r\n";
    $out .= "Host: " . $parts['host'] . "\r\n";
    $out .= "Content-Type: application/x-www-form-urlencoded\r\n";
    $out .= "Content-Length: " . strlen($post_string) . "\r\n";
    $out .= "Connection: Close\r\n\r\n";
    // Data goes in the request body for a POST request
    if ('POST' == $type && isset($post_string)) $out .= $post_string;
    fwrite($fp, $out);
    fclose($fp);
}

function make_post($url, $params, $type = 'POST')
{
    $line = "";
    foreach ($params as $key => $val) {
        if (is_array($val)) $val = implode(',', $val);
        $post_params[] = $key . '=' . urlencode($val);
    }
    $post_string = implode('&', $post_params);
    $parts = parse_url($url);
    $fp = fsockopen($parts['host'], isset($parts['port']) ? $parts['port'] : 80, $errno, $errstr, 30);
    if ('GET' == $type) $parts['path'] .= '?' . $post_string;
    $out = "$type " . $parts['path'] . " HTTP/1.1\r\n";
    $out .= "Host: " . $parts['host'] . "\r\n";
    if (isset($params['sid']))
        $out .= "Cookie: PHPSESSID=" . $params['sid'] . "; path=/;\r\n";
    $out .= "Content-Type: application/x-www-form-urlencoded\r\n";
    $out .= "Content-Length: " . strlen($post_string) . "\r\n";
    $out .= "Connection: Close\r\n\r\n";
    // Data goes in the request body for a POST request
    if ('POST' == $type && isset($post_string)) $out .= $post_string;
    fwrite($fp, $out);
    while (!feof($fp)) $line .= fread($fp, 4096);
    fclose($fp);
    $pos = strpos($line, "\r\n\r\n");
    $head = substr($line, 0, $pos);    //http head
    $status = substr($head, 0, strpos($head, "\r\n"));    //http status line
    $body = substr($line, $pos + 4, strlen($line) - ($pos + 4)); //page body
    //$body=  str_replace("&lt;","<",$body);
    //$body=  str_replace("&gt;",">",$body);
    //Log::info($body);
    return trim($body);
}

function get_url_content($url, $params = array(), $header = array(), $method = 'post', $patype = 0, $cookie = 0)
{
    $timeout = 120; //curl超时时间$header = array('apikey:apikey');
    if ($params == "") $method = 'get'; //这个先兼容以前的后期去掉
    $strCookie = isset($params['sid']) ? "PHPSESSID=" . $params['sid'] : "";
    if (strtolower($method) == "get" && !empty($params)) {
        if (strpos($url, '?') == false) $url = $url . "?";
        $url = $url . '&' . http_build_query($params, '', '&');
    }
    if (function_exists('curl_init')) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, trim($url));
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        $header = explode('://', $url);
        if ($header[0] == 'https') {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        $show_header = 0;
        if ($cookie) $show_header = 1;
        curl_setopt($ch, CURLOPT_HEADER, $show_header); //显示返回的Header区域内容
        curl_setopt($ch, CURLOPT_COOKIE, $strCookie);
        if (strtolower($method) == "post") {
            curl_setopt($ch, CURLOPT_POST, true); //可能会提交JSON数据
            //            if(is_array($params)){
            //                Log::info('url =='.$url.'#####请求参数 =='.http_build_query($params, '', '&').'#######header=='.json_encode($header));
            //            }
            if ($patype) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
            } else {
                curl_setopt($ch, CURLOPT_POSTFIELDS, is_array($params) ? http_build_query($params, '', '&') : $params);
            }
        }
        if (strtolower($method) == "put") {
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); //可能会提交JSON数据
            if ($patype) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
            } else {
                curl_setopt($ch, CURLOPT_POSTFIELDS, is_array($params) ? http_build_query($params, '', '&') : $params);
            }
        }
        try {
            $file_contents = curl_exec($ch);
            $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
            if (empty($file_contents)) $file_contents = curl_error($ch);
            if ($cookie) {
                // 解析HTTP数据流
                list($header, $body) = explode("\r\n\r\n", $file_contents);
                // 解析COOKIE
                preg_match("/set\-cookie:([^\r\n]*)/i", $header, $matches);
                //请求的时候headers 带上cookie就可以了
                $cookie = explode(';', $matches[1])[0];
                return $cookie;
            }
        } catch (Exception $e) {
            $file_contents = "Line:" . $e->getLine() . "Err:" . $e->getMessage();
        } finally {
            curl_close($ch);
        }
    } else {
        $context = array();
        $context['http'] = array(
            'timeout' => 60,
            'method' => 'POST',
            'header' => "Content-Type: application/x-www-form-urlencoded\r\n" .
                "Cookie: " . $strCookie . ";\r\n" . @implode('\r\n', $header),
            'content' => http_build_query($params, '', '&'),
        );
        $file_contents = file_get_contents($url, 0, stream_context_create($context));
    }
    if (strstr($file_contents, "HTTP/1.1") && count(explode("\r\n\r\n", $file_contents, 2)) > 1)
        list($header, $file_contents) = explode("\r\n\r\n", $file_contents, 2); // 200 OK
    return trim($file_contents); //strip_tags
}

//上游不能http 直接访问，需要伪造 浏览器请求 加的参数  curl_setopt($ch, CURLOPT_USERAGENT,  "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0");
function get_url_content1($url, $params = array(), $header = array(), $method = 'post', $patype = 0)
{
    $timeout = 120; //curl超时时间$header = array('apikey:apikey');
    if ($params == "") $method = 'get'; //这个先兼容以前的后期去掉
    $strCookie = isset($params['sid']) ? "PHPSESSID=" . $params['sid'] : "";
    if (strtolower($method) == "get" && !empty($params)) {
        if (strpos($url, '?') == false) $url = $url . "?";
        $url = $url . '&' . http_build_query($params, '', '&');
    }
    if (function_exists('curl_init')) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, trim($url));
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        $header = explode('://', $url);
        if ($header[0] == 'https') {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_HEADER, 0); //显示返回的Header区域内容
        curl_setopt($ch, CURLOPT_COOKIE, $strCookie);
        curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0");
        if (strtolower($method) == "post") {
            curl_setopt($ch, CURLOPT_POST, true); //可能会提交JSON数据
            //            if(is_array($params)){
            //                Log::info('url =='.$url.'#####请求参数 =='.http_build_query($params, '', '&').'#######header=='.json_encode($header));
            //            }
            if ($patype) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
            } else {
                curl_setopt($ch, CURLOPT_POSTFIELDS, is_array($params) ? http_build_query($params, '', '&') : $params);
            }
        }
        if (strtolower($method) == "put") {
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); //可能会提交JSON数据
            if ($patype) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
            } else {
                curl_setopt($ch, CURLOPT_POSTFIELDS, is_array($params) ? http_build_query($params, '', '&') : $params);
            }
        }
        try {
            $file_contents = curl_exec($ch);
            // var_dump($file_contents,7777777777777);
            $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
            if (empty($file_contents)) $file_contents = curl_error($ch);
        } catch (Exception $e) {
            $file_contents = "Line:" . $e->getLine() . "Err:" . $e->getMessage();
        } finally {
            curl_close($ch);
        }
    } else {
        $context = array();
        $context['http'] = array(
            'timeout' => 60,
            'method' => 'POST',
            'header' => "Content-Type: application/x-www-form-urlencoded\r\n" .
                "Cookie: " . $strCookie . ";\r\n" . @implode('\r\n', $header),
            'content' => http_build_query($params, '', '&'),
        );
        $file_contents = file_get_contents($url, 0, stream_context_create($context));
    }
    if (strstr($file_contents, "HTTP/1.1") && count(explode("\r\n\r\n", $file_contents, 2)) > 1)
        list($header, $file_contents) = explode("\r\n\r\n", $file_contents, 2); // 200 OK
    return trim($file_contents); //strip_tags
}

function Public_Http_Post($url, $param)
{
    $oCurl = curl_init();
    if (stripos($url, "https://") !== FALSE) {
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
    }
    if (is_string($param)) {
        $strPOST = $param;
    } else {
        $aPOST = array();
        foreach ($param as $key => $val) {
            $aPOST[] = $key . "=" . urlencode($val);
        }
        $strPOST = join("&", $aPOST);
    }
    curl_setopt($oCurl, CURLOPT_URL, $url);
    curl_setopt($oCurl, CURLOPT_SAFE_UPLOAD, false);
    curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($oCurl, CURLOPT_POST, true);
    curl_setopt($oCurl, CURLOPT_POSTFIELDS, $strPOST);
    $sContent = curl_exec($oCurl);
    $aStatus = curl_getinfo($oCurl);
    curl_close($oCurl);
    if (intval($aStatus["http_code"]) == 200) {
        return $sContent;
    } else {
        return false;
    }
}

/*
 * 把一个大于0的整数和，转换为二进制各位表达数的数组
 * 比如 30 = 16 + 8 + 4
 *   输入 30
 *   输出 [4，8，16]
 */
function sum2array($d)
{
    $a = array();
    $m = 1;
    $chars = str_split(decbin($d));
    foreach (array_reverse($chars) as $char) {
        if ($char == '1')
            $a[] = $m;
        $m = $m * 2;
    }
    return $a;
}

/**
 * 将数组转换成树
 * @param array $sourceArr 要转换的数组
 * @param string $key 数组中确认父子的key，例子中为“id”
 * @param string $parentKey 数组中父key，例子中为“parentId”
 * @param type $childrenKey 要在树节点上索引子节点的key，例子中为“children”
 * @return array 返回生成的树
 */
function arrayToTree($sourceArr, $key, $parentKey, $childrenKey)
{
    $tempSrcArr = array();

    $allRoot = TRUE;
    foreach ($sourceArr as $v) {
        $isLeaf = TRUE;
        foreach ($sourceArr as $cv) {
            if (($v[$key]) != $cv[$key]) {
                if ($v[$key] == $cv[$parentKey]) {
                    $isLeaf = FALSE;
                }
                if ($v[$parentKey] == $cv[$key]) {
                    $allRoot = FALSE;
                }
            }
        }
        if ($isLeaf) {
            $leafArr[$v[$key]] = $v;
        }
        $tempSrcArr[$v[$key]] = $v;
    }
    if ($allRoot) {
        return $tempSrcArr;
    } else {
        unset($v, $cv, $sourceArr, $isLeaf);
        foreach ($leafArr as $v) {
            if (isset($tempSrcArr[$v[$parentKey]])) {
                $tempSrcArr[$v[$parentKey]][$childrenKey] = (isset($tempSrcArr[$v[$parentKey]][$childrenKey]) && is_array($tempSrcArr[$v[$parentKey]][$childrenKey])) ? $tempSrcArr[$v[$parentKey]][$childrenKey] : array();
                array_push($tempSrcArr[$v[$parentKey]][$childrenKey], $v);
                unset($tempSrcArr[$v[$key]]);
            }
        }
        unset($v);
        return arrayToTree($tempSrcArr, $key, $parentKey, $childrenKey);
    }
}

function getTree($data, $pid = 0, $key = 'id', $pKey = 'parentId', $childKey = 'child', $maxDepth = 0)
{
    static $depth = 0;
    $tree = array();
    $depth++;
    if (intval($maxDepth) <= 0) {
        $maxDepth = count($data) * count($data);
    }
    if ($depth > $maxDepth) {
        return $tree; //exit("error recursion:max recursion depth {$depth}{$maxDepth}");
    }

    foreach ($data as $rk => $rv) {
        //     	echo "<pre>";print_r($pid);
        //     	echo "<pre>";print_r($rv[$pKey]);exit;
        if ($rv[$pKey] == $pid) {
            $rv[$childKey] = getTree($data, $rv[$key], $key, $pKey, $childKey, $maxDepth);
            //if( count($rv[$childKey])==0 )    unset($rv[$childKey]);
            $tree[] = $rv;
        }
    }
    return $tree;
}

/*** 根据两点间经纬度坐标（double值），计算两点间距离，单位为米 */
function getDistance($lng1, $lat1, $lng2, $lat2)
{
    $earthRadius = 6367000;
    if (strstr($lng1, '.') == 0) {
        $lng1 = substr($lng1, 0, 3) . "." . substr($lng1, 3, 6);
        $lat1 = substr($lat1, 0, 2) . "." . substr($lat1, 2, 6);
        $lng2 = substr($lng2, 0, 3) . "." . substr($lng2, 3, 6);
        $lat2 = substr($lat2, 0, 2) . "." . substr($lat2, 2, 6);
    }
    $lat1 = ($lat1 * pi()) / 180;
    $lng1 = ($lng1 * pi()) / 180;

    $lat2 = ($lat2 * pi()) / 180;
    $lng2 = ($lng2 * pi()) / 180;

    $calcLong = $lng2 - $lng1;
    $calcLat = $lat2 - $lat1;
    $stepOne = pow(sin($calcLat / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLong / 2), 2);
    $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
    $Distance = $earthRadius * $stepTwo;
    return round($Distance) / 1000;
}

/**
 * @param lat 纬度 lon 经度 raidus 单位米
 * return minLat,minLng,maxLat,maxLng
 */
function getAround($lon, $lat, $raidus)
{
    $PI = 3.14159265;
    $itude = array();
    $degree = (24901 * 1609) / 360.0;
    $raidusMile = $raidus * 1000;
    // if( strstr($lon,'.') )
    // {
    //     $lon=$lon*1000000;
    //     $lat=$lat*1000000;
    // }

    $dpmLat = 1 / $degree;
    $radiusLat = $dpmLat * $raidusMile;
    $itude['lat'][] = ($lat - $radiusLat);
    $itude['lat'][] = ($lat + $radiusLat);

    $mpdLng = $degree * cos($lat * ($PI / 180));
    $dpmLng = 1 / $mpdLng;
    $radiusLng = $dpmLng * $raidusMile;
    $itude['lng'][] = ($lon - $radiusLng);
    $itude['lng'][] = ($lon + $radiusLng);
    return $itude;
}

function Output($fileContent, $showname)
{
    $downloadType = "attachment"; //inline内嵌显示//attachment 下载显示
    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Content-Type: application/force-download");
    header("Content-Type: application/octet-stream");
    header("Content-Type: application/download");
    header("Content-Disposition: $downloadType; filename=" . $showname);
    header('Content-Encoding: none');
    header("Content-Transfer-Encoding: binary");
    header("Content-Length: " . strlen($fileContent));
    echo($fileContent);
    exit;
}

//字符串拼接
function format()
{
    $args = func_get_args();
    if (count($args) == 0) {
        return;
    }
    if (count($args) == 1) {
        return $args[0];
    }
    $str = array_shift($args);
    $str = preg_replace_callback('/\\{(0|[1-9]\\d*)\\}/', create_function('$match', '$args=' . var_export($args, true) . '; return isset($args[$match[1]])? $args[$match[1]]:$match[0];'), $str);

    return $str;
}

/*
* 将excel转换为数组 by aibhsc
* */
function format_excel2array($filePath = '', $sheet = 0)
{
    require('includes/PHPExcel.php'); //引入PHP EXCEL类
    if (empty($filePath) or !file_exists($filePath)) {
        die('file not exists');
    }
    $PHPReader = new PHPExcel_Reader_Excel2007();        //建立reader对象
    if (!$PHPReader->canRead($filePath)) {
        $PHPReader = new PHPExcel_Reader_Excel5();
        if (!$PHPReader->canRead($filePath)) {
            echo 'no Excel';
            return;
        }
    }
    $PHPExcel = $PHPReader->load($filePath);        //建立excel对象
    $currentSheet = $PHPExcel->getSheet($sheet);        //**读取excel文件中的指定工作表*/
    $allColumn = $currentSheet->getHighestColumn();        //**取得最大的列号*/
    $allRow = $currentSheet->getHighestRow();        //**取得一共有多少行*/
    $data = array();
    for ($rowIndex = 1; $rowIndex <= $allRow; $rowIndex++) {        //循环读取每个单元格的内容。注意行从1开始，列从A开始
        for ($colIndex = 'A'; $colIndex <= $allColumn; $colIndex++) {
            $addr = $colIndex . $rowIndex;
            $cell = $currentSheet->getCell($addr)->getValue();
            if ($cell instanceof PHPExcel_RichText) { //富文本转换字符串
                $cell = $cell->__toString();
            }
            $data[$rowIndex][$colIndex] = $cell;
        }
    }
    return $data;
}

function gEnv($key = '', $name = '.env')
{
    $configPath = config_path() . DIRECTORY_SEPARATOR . $name . '.env';
    if (!\File::exists($configPath)) {
        return FALSE;
    }

    $data = collect(file($configPath, FILE_IGNORE_NEW_LINES));
    $data->transform(function ($item) {
        list($key, $value) = explode('=', $item);
        $list[$key] = $value;

        return $list;
    });

    $list = $data->toArray();
    foreach ($list as $value) {
        foreach ($value as $k => $v) {
            $arr[$k] = $v;
        }
    }
    if (!empty($key)) {
        return $arr[$key];
    }
    return $arr;
}

function modifyEnv(array $data)
{
    $envPath = base_path() . DIRECTORY_SEPARATOR . '.env';

    $contentArray = collect(file($envPath, FILE_IGNORE_NEW_LINES));

    $contentArray->transform(function ($item) use ($data) {
        foreach ($data as $key => $value) {
            if (str_contains($item, $key)) {
                return $key . '=' . $value;
            }
        }

        return $item;
    });

    $content = implode($contentArray->toArray(), "\n");

    \File::put($envPath, $content);
}

function is_json($string)
{
    json_decode($string);
    return (json_last_error() == JSON_ERROR_NONE);
}

function is_xml($string)
{
    $xml_parser = xml_parser_create();
    if (!xml_parse($xml_parser, $string, true)) {
        xml_parser_free($xml_parser);
        return false;
    } else {
        return (json_decode(json_encode(simplexml_load_string($string)), true));
    }
}

function getTokenById($arr)
{
    return \Firebase\JWT\JWT::encode($arr, 'hk', 'HS256');
}

function getUserIdByToken($Token)
{
    $arr = \Firebase\JWT\JWT::decode($Token, 'hk', 'HS256');
    return $arr->id;
}

function getYhTokenById($arr)
{
    return \Firebase\JWT\JWT::encode($arr, 'hk', 'HS256');
}

function getYhUserIdByToken($Token)
{
    $arr = \Firebase\JWT\JWT::decode($Token, 'hk', 'HS256');
    return $arr->id;
}

function dump($var)
{
    var_dump($var);
}

function object2array($object)
{
    return @json_decode(@json_encode($object), 1);
}

function is_idcard($id)
{
    $id = strtoupper($id);
    $regx = "/(^\d{15}$)|(^\d{17}([0-9]|X)$)/";
    $arr_split = array();
    if (!preg_match($regx, $id)) {
        return 0;
    }
    if (15 == strlen($id)) //检查15位
    {
        $regx = "/^(\d{6})+(\d{2})+(\d{2})+(\d{2})+(\d{3})$/";
        @preg_match($regx, $id, $arr_split);
        //检查生日日期是否正确
        $dtm_birth = "19" . $arr_split[2] . '/' . $arr_split[3] . '/' . $arr_split[4];
        if (!strtotime($dtm_birth)) {
            return 0;
        } else {
            return 1;
        }
    } else //检查18位
    {
        $regx = "/^(\d{6})+(\d{4})+(\d{2})+(\d{2})+(\d{3})([0-9]|X)$/";
        @preg_match($regx, $id, $arr_split);
        $dtm_birth = $arr_split[2] . '/' . $arr_split[3] . '/' . $arr_split[4];
        if (!strtotime($dtm_birth)) //检查生日日期是否正确
        {
            return 0;
        } else {
            //检验18位身份证的校验码是否正确。
            //校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。
            $arr_int = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
            $arr_ch = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
            $sign = 0;
            for ($i = 0; $i < 17; $i++) {
                $b = (int)$id[$i];
                $w = $arr_int[$i];
                $sign += $b * $w;
            }
            $n = $sign % 11;
            $val_num = $arr_ch[$n];
            if ($val_num != substr($id, 17, 1)) {
                return 0;
            } else {
                return 1;
            }
        }
    }
}

function getAgeByID($id)
{

    //过了这年的生日才算多了1周岁
    if (empty($id)) return '';
    $date = strtotime(substr($id, 6, 8));
    //获得出生年月日的时间戳
    $today = strtotime('today');
    //获得今日的时间戳
    $diff = floor(($today - $date) / 86400 / 365);
    //得到两个日期相差的大体年数

    //strtotime加上这个年数后得到那日的时间戳后与今日的时间戳相比
    $age = strtotime(substr($id, 6, 8) . ' +' . $diff . 'years') > $today ? ($diff + 1) : $diff;

    return $age;
}

/*
 * 获取上个月日期
 */
function getlastMonthDays($date)
{
    $timestamp = strtotime($date);
    $firstday = date('Y-m-01', strtotime(date('Y', $timestamp) . '-' . (date('m', $timestamp) - 1) . '-01'));
    $lastday = date('Y-m-d', strtotime("$firstday +1 month -1 day"));
    $lastday = $lastday . ' ' . date('H:i:s', $timestamp);
    return $lastday;
}

function objName($channel_pname)
{
    $pname = $channel_pname;
    $cmiotjiangsugxc = ['cmiotjiangsujdjh', 'cmiotjiangsuoem', 'cmiotjiangsu', 'cmiotjiangsu30', 'cmiotjiangsu30jckf', 'cmiotjiangsugxcxx', 'cmiotjiangsuqx', 'cmiotjiangsugxccs'];
    if (in_array($channel_pname, $cmiotjiangsugxc)) {
        $pname = 'cmiotjiangsugxc';
    }
    $cmiotguangzhou = ['cmiotguangzhouoem', 'cmiotgzqx', 'cmiotguangzhouqxgxc'];
    if (in_array($channel_pname, $cmiotguangzhou)) {
        $pname = 'cmiotguangzhou';
        if ($channel_pname == 'cmiotgzqx') $pname = 'cmiotgztc';
    }
    $ct10649qxgxc = ['ct10649qxdingzhi', 'ct10649qxdingzhixx', 'ct10649qxgxcxx', 'ct10649qxgxc30'];
    if (in_array($channel_pname, $ct10649qxgxc)) {
        $pname = 'ct10649qxgxc';
    }
    $cmiotqxgxc = ['cmiotqxdingzhi', 'cmiothenan', 'cmiothenanoem'];
    if (in_array($channel_pname, $cmiotqxgxc)) {
        $pname = 'cmiotqxgxc';
    }
    $hebei = ['hebeioem', 'hebeioemsm', 'hebeidasheng', 'hebeiqx', 'hebei30', 'hebei30jckf'];
    if (in_array($channel_pname, $hebei)) {
        $pname = 'hebei';
    }
    $hebeioemxx = ['hebeioemxx'];
    if (in_array($channel_pname, $hebeioemxx)) {
        $pname = 'hebeioemxx';
    }
    $cmiotbeijin = ['cmiotbeijinqx'];
    if (in_array($channel_pname, $cmiotbeijin)) {
        $pname = 'cmiotbeijin';
    }
    $cmiotonelink = ['cmiotonelinkqx', 'cmiotonelink30', 'cmiotonelinkqx30jckf'];
    if (in_array($channel_pname, $cmiotonelink)) {
        $pname = 'cmiotoneLink';
    }
    $cmiotshandong = ["cmiotshandongqxgxc", "cmiotsdqxgxc"];
    if (in_array($channel_pname, $cmiotshandong)) $pname = 'cmiotshandong';
    $cmiotoneLinkWeb = ['cmiotonelinkWebqx'];
    if (in_array($channel_pname, $cmiotoneLinkWeb)) {
        $pname = 'CmiotoneLinkWeb';
    }
    $woxindaqxgxc = ['woxindaqxgxc'];
    if (in_array($channel_pname, $woxindaqxgxc)) {
        $pname = 'Woxinda';
    }
    $zjhuishuqxgxc = ['zjhuishuqxgxc'];
    if (in_array($channel_pname, $zjhuishuqxgxc)) {
        $pname = 'Zjhuishu';
    }
    $iioneqxgxc = ['iioneqxgxc'];
    if (in_array($channel_pname, $iioneqxgxc)) {
        $pname = 'Iione';
    }
    $zqltqxgxc = ['zqltqxgxc'];
    if (in_array($channel_pname, $zqltqxgxc)) {
        $pname = 'Zqlt';
    }
    $jinbiaolongqxgxc = ['jinbiaolongqxgxc'];
    if (in_array($channel_pname, $jinbiaolongqxgxc)) {
        $pname = 'Jinbiaolong';
    }
    $seecomqxgxc = ['seecomqxgxc'];
    if (in_array($channel_pname, $seecomqxgxc)) {
        $pname = 'Seecom';
    }
    $seecomOnelinkqxgxc = ['seecomOnelinkqxgxc'];
    if (in_array($channel_pname, $seecomOnelinkqxgxc)) {
        $pname = 'SeecomOnelink';
    }
    $cmiotShanxiqxgxc = ['cmiotShanxiqxgxc'];
    if (in_array($channel_pname, $cmiotShanxiqxgxc)) {
        $pname = 'CmiotShanxi';
    }
    $m10646dcpqx = ['m10646dcpqx'];
    if (in_array($channel_pname, $m10646dcpqx)) {
        $pname = 'M10646dcp';
    }
    $tibiotqxgxc = ['tibiotqxgxc'];
    if (in_array($channel_pname, $tibiotqxgxc)) {
        $pname = 'Tibiot';
    }
    $ezhuboqxgxc = ['ezhuboqxgxc'];
    if (in_array($channel_pname, $ezhuboqxgxc)) {
        $pname = 'Ezhubo';
    }
    $xiyanqxgxc = ['xiyanqxgxc'];
    if (in_array($channel_pname, $xiyanqxgxc)) {
        $pname = 'Xiyan';
    }
    $iotSalesqxgxc = ['iotSalesqxgxc'];
    if (in_array($channel_pname, $iotSalesqxgxc)) {
        $pname = 'IotSales';
    }
    $jdwlkjm2mxinqxgxc = ['jdwlkjm2mxinqxgxc'];
    if (in_array($channel_pname, $jdwlkjm2mxinqxgxc)) {
        $pname = 'Jdwlkjm2mxin';
    }
    $beijingbwaenewqxgxc = ['beijingbwaenewqxgxc'];
    if (in_array($channel_pname, $beijingbwaenewqxgxc)) {
        $pname = 'Beijingbwaenew';
    }
    $varefamuleiqxgxc = ['varefamuleiqxgxc'];
    if (in_array($channel_pname, $varefamuleiqxgxc)) {
        $pname = 'Varefamulei';
    }
    $lenovoqxgxc = ['lenovoqxgxc'];
    if (in_array($channel_pname, $lenovoqxgxc)) {
        $pname = 'Lenovo';
    }
    $huidesichuang1qxgxc = ['huidesichuang1qxgxc'];
    if (in_array($channel_pname, $huidesichuang1qxgxc)) {
        $pname = 'Huidesichuang1';
    }
    $cmioLianzhouqxgxc = ['cmioLianzhouqxgxc'];
    if (in_array($channel_pname, $cmioLianzhouqxgxc)) {
        $pname = 'CmioLianzhou';
    }
    $topspeedqxgxc = ['topspeedqxgxc'];
    if (in_array($channel_pname, $topspeedqxgxc)) {
        $pname = 'Topspeed';
    }
    $wsljkqxgxc = ['wsljkqxgxc'];
    if (in_array($channel_pname, $wsljkqxgxc)) {
        $pname = 'Wsljk';
    }
    $wlwpinCtOqxgxc = ['wlwpinCtOqxgxc'];
    if (in_array($channel_pname, $wlwpinCtOqxgxc)) {
        $pname = 'WlwpinCtO';
    }
    $wlwpinqxgxc = ['wlwpinqxgxc'];
    if (in_array($channel_pname, $wlwpinqxgxc)) {
        $pname = 'Wlwpin';
    }
    $wlgjiaqxgxc = ['wlgjiaqxgxc'];
    if (in_array($channel_pname, $wlgjiaqxgxc)) {
        $pname = 'Wlgjia';
    }
    $tianchaoqxgxc = ['tianchaoqxgxc'];
    if (in_array($channel_pname, $tianchaoqxgxc)) {
        $pname = 'Tianchao';
    }
    $szsmqxgxc = ['szsmqxgxc'];
    if (in_array($channel_pname, $szsmqxgxc)) {
        $pname = 'Szsm';
    }
    $kancloudNewqxgxc = ['kancloudNewqxgxc'];
    if (in_array($channel_pname, $kancloudNewqxgxc)) {
        $pname = 'KancloudNew';
    }
    $zwyxitqxgxc = ['zwyxitqxgxc'];
    if (in_array($channel_pname, $zwyxitqxgxc)) {
        $pname = 'Zwyxit';
    }
    return $pname;
}

function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0)
{
    // 动态密匙长度，相同的明文会生成不同密文就是依靠动态密匙
    $ckey_length = 4;

    // 密匙
    $key = md5($key ? $key : $GLOBALS['discuz_auth_key']);

    // 密匙a会参与加解密
    $keya = md5(substr($key, 0, 16));
    // 密匙b会用来做数据完整性验证
    $keyb = md5(substr($key, 16, 16));
    // 密匙c用于变化生成的密文
    $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length) :
        substr(md5(microtime()), -$ckey_length)) : '';
    // 参与运算的密匙
    $cryptkey = $keya . md5($keya . $keyc);
    $key_length = strlen($cryptkey);
    // 明文，前10位用来保存时间戳，解密时验证数据有效性，10到26位用来保存$keyb(密匙b)，
    //解密时会通过这个密匙验证数据完整性
    // 如果是解码的话，会从第$ckey_length位开始，因为密文前$ckey_length位保存 动态密匙，以保证解密正确
    $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) :
        sprintf('%010d', $expiry ? $expiry + time() : 0) . substr(md5($string . $keyb), 0, 16) . $string;
    $string_length = strlen($string);
    $result = '';
    $box = range(0, 255);
    $rndkey = array();
    // 产生密匙簿
    for ($i = 0; $i <= 255; $i++) {
        $rndkey[$i] = ord($cryptkey[$i % $key_length]);
    }
    // 用固定的算法，打乱密匙簿，增加随机性，好像很复杂，实际上对并不会增加密文的强度
    for ($j = $i = 0; $i < 256; $i++) {
        $j = ($j + $box[$i] + $rndkey[$i]) % 256;
        $tmp = $box[$i];
        $box[$i] = $box[$j];
        $box[$j] = $tmp;
    }
    // 核心加解密部分
    for ($a = $j = $i = 0; $i < $string_length; $i++) {
        $a = ($a + 1) % 256;
        $j = ($j + $box[$a]) % 256;
        $tmp = $box[$a];
        $box[$a] = $box[$j];
        $box[$j] = $tmp;
        // 从密匙簿得出密匙进行异或，再转成字符
        $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
    }
    if ($operation == 'DECODE') {
        // 验证数据有效性，请看未加密明文的格式
        if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) &&
            substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16)
        ) {
            return substr($result, 26);
        } else {
            return '';
        }
    } else {
        // 把动态密匙保存在密文里，这也是为什么同样的明文，生产不同密文后能解密的原因
        // 因为加密后的密文可能是一些特殊字符，复制过程可能会丢失，所以用base64编码
        return $keyc . str_replace('=', '', base64_encode($result));
    }
}

//    参数加密
function encryption_param($data, $str = 'sltx112')
{
    ksort($data);
    $wait = "";
    foreach ($data as $key => $val) {
        $wait .= $key . '=' . $val . '&';
    }
    $wait = substr($wait, 0, -1);
    $sign = authcode($wait, 'ENCODE', $str);
    return $sign;
}

//  参数解密 返回 数组
function decrypt_param($sign, $str = 'sltx112')
{
    $sign_decode = authcode($sign, 'DECODE', $str);
    $arrays = explode('&', $sign_decode);
    $param = array();
    foreach ($arrays as $array) {
        $e = explode('=', $array);
        if (isset($e[1]) && isset($e[0])) $param[$e[0]] = $e[1];
    }
    return $param;
}

//判断是否为日期格式
function isdate($time)
{
    $isdate = preg_match("/^[0-9]{4}(\-|\/)[0-9]{1,2}(\\1)[0-9]{1,2}(|\s+[0-9]{1,2}(|:[0-9]{1,2}(|:[0-9]{1,2})))$/", $time);
    return $isdate;
}

/*
 * day1 时间小
 * day2 时间大
 * 如果填反 两个时间间隔天数返回 0天
 */
function diffBetweenTwoDays($day1, $day2)
{
    $endtime = strtotime($day2); //时间大
    $starttime = strtotime($day1); //时间小
    $day_arr = array();
    while (($starttime = strtotime('+1 day', $starttime)) <= $endtime) {
        $day_arr[] = date('Y-m-d', $starttime); // 取得递增天;
    }
    $day_num = count($day_arr);
    return $day_num;
}

//判断是否有中文字符
function isChinesecharacters($str)
{
}

function SHA256Hex($str)
{
    $re = hash('sha256', $str, true);
    return bin2hex($re);
}

function get_city_name($id)
{
    return DB::table('region')->where('region_id', $id)->value('REGION_NAME');
}

if (!function_exists('bcrypt')) {
    /**
     * Hash the given value.
     *
     * @param string $value
     * @param array $options
     * @return string
     */
    function bcrypt($value, $options = [])
    {
        return app('hash')->make($value, $options);
    }
}
if (!function_exists('getStrLen')) {
    /**
     * string the given value.
     *
     * @param string $value
     * @return string
     */
    function getStrLen($value)
    {
        $j = 0;
        for ($i = 0; $i < mb_strlen($value); $i++) {
            if (ord(mb_substr($value, $i, 1)) > 0xa0) {
                $j++;
            }
        }
        return $j;
    }
}

/**
 * @brief 获取网站根路径
 * @param string $protocol 协议  默认为http协议，不需要带'://'
 * @return String $baseUrl  网站根路径
 *
 */
function getHost()
{
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
    $host = isset($_SERVER['HTTP_X_FORWARDED_HOST']) ? $_SERVER['HTTP_X_FORWARDED_HOST'] : (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '');
    $baseUrl = $protocol . $host . '/';

    return $baseUrl;
}

/**
 * 把键值对字符串分割成数组
 * @param $str
 * @param string $delimiter
 * @return array
 */
function strToKeyValArr($str, $delimiter = ';')
{
    $result = array();
    $arr = explode($delimiter, $str);

    foreach ($arr as $item) {
        $data = explode(':', trim($item));
        if (count($data) == 2) {
            $result[$data[0]] = $data[1];
        }
    }
    // var_dump($result);
    return $result;
}

function strToKeyValArrTwo($str, $strOne = '=', $delimiter = ';')
{
    $result = array();
    $arr = explode($delimiter, $str);

    foreach ($arr as $item) {
        $data = explode((!empty($strOne) ? $strOne : ':'), trim($item));
        if (count($data) == 2) {
            $result[$data[0]] = urldecode($data[1]);
        }
    }
    // var_dump($result);
    return $result;
}

function get_content($url, $header_array, $post_value)
{
    //初始化
    $curl = curl_init();
    //设置抓取的url
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_POST, true);
    //设置头文件的信息作为数据流输出
    curl_setopt($curl, CURLOPT_HEADER, 0);
    //设为TRUE把curl_exec()结果转化为字串，而不是直接输出
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
    //传递 header 头
    curl_setopt($curl, CURLOPT_HTTPHEADER, $header_array);
    //对认证证书来源的检查
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    //从证书中检查SSL加密算法是否存在
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    //post请求
    curl_setopt($curl, CURLOPT_POST, 1);
    //设置提交的字符串
    curl_setopt($curl, CURLOPT_POSTFIELDS, ($post_value)); //http_build_query(
    //设置超时时间
    curl_setopt($curl, CURLOPT_TIMEOUT, 300);
    $output = curl_exec($curl);
    if (curl_errno($curl)) {
        return false;
    }
    //    var_dump($output);
    curl_close($curl);
    return $output;
}

/**
 * 检查多层目录（例如：attach/photo/pic）
 * @param string $dir
 */
function confirmDir($dir = '')
{
    if ($dir) {
        $dirArr = explode('/', $dir);

        $fileDir = public_path();

        foreach ($dirArr as $item) {
            $fileDir = $fileDir . '/' . $item;
            if (!is_dir($fileDir)) {
                $res = @mkdir($fileDir, 0777);
                // var_dump($fileDir,'111111'.$res.'11111');
                // var_dump($res,'2222222222');
            }
        }
    }
}

function str_replace_once($needle, $replace, $haystack)
{
    $pos = strpos($haystack, $needle);
    if ($pos === false) {
        return $haystack;
    }
    return substr_replace($haystack, $replace, $pos, strlen($needle));
}

if (!function_exists('generate_uuid')) {
    /**
     * 获取uuid
     * @return string
     */
    function generate_uuid()
    {
        $charId = md5(uniqid(rand(), true));
        $hyphen = chr(45); // "-"
        $uuid = substr($charId, 0, 8) . $hyphen
            . substr($charId, 8, 4) . $hyphen
            . substr($charId, 12, 4) . $hyphen
            . substr($charId, 16, 4) . $hyphen
            . substr($charId, 20, 12);
        return $uuid;
    }
}
if (!function_exists('usfirstArr')) {
    /**
     * 获取uuid
     * @return string
     */
    function usfirstArr($arr)
    {
        if (is_object($arr)) {
            $arr = json_decode(json_encode($arr), true);
        }
        $returnData = [];
        foreach ($arr as $key => $v) {
            // 需要将 key _a 字段 转化为A
            $arrays = [];
            if (!empty($v) && is_array($v)) {
                foreach ($v as $k => $val) {
                    if (strripos($k, '_') !== false) {
                        $arr = explode('_', $k);
                        for ($i = 1; $i < count($arr); $i++) {
                            $arr[$i] = ucfirst($arr[$i]);
                        }
                        $arrays[implode('', $arr)] = $val;
                    } else {
                        $arrays[$k] = $val;
                    }
                }
                $returnData[] = $arrays;
                continue;
            }
            if (strripos($key, '_') !== false) {
                $arr = explode('_', $key);
                for ($i = 1; $i < count($arr); $i++) {
                    $arr[$i] = ucfirst($arr[$i]);
                }
                $returnData[implode('', $arr)] = $v;
            } else {
                $returnData[$key] = $v;
            }
        }
        return $returnData;
    }
}
//将 大写转化为_小写
if (!function_exists('lowerFitstArr')) {
    function lowerFitstArr($arr)
    {
        if (is_object($arr)) {
            $arr = json_decode(json_encode($arr), true);
        }
        $return = [];
        if (!empty($arr)) {
            foreach ($arr as $key => $v) {
                //值不变 将key转化
                $key = preg_replace('/([A-Z])/', "_$1", $key, 1);
                $key = strtolower($key);
                if (is_array($v) || is_object($v)) {
                    $return[$key] = lowerFitstArr($v);
                    continue;
                }
                $return[$key] = $v;
            }
        }
        return $return;
    }
}
//获取一段供销商字符串
if (!function_exists('productSuppiler')) {
    function productSuppiler($length = 8)
    {
        $str = '';
        $arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'W', 'w', 'X', 'Y', 'Z', 'x', 'y', 'z', 't', 'T', 'V', 'v'];
        $res = array_rand($arr, $length);
        foreach ($res as $key => $v) {
            $str .= $arr[$v];
        }
        return $str;
    }
}
// 生成订单号
if (!function_exists('creatOrderNums')) {
    function creatOrderNums($pix = '')
    {
        $str = $pix . date('YmdHis');
        list($microsecond, $time) = explode(' ', microtime());
        $str .= str_replace('.', '', ($microsecond * 1000));
        if (strlen($str) < 20) {
            // 使用
            $speet = mt_rand(0, 9);
            $nums = 20 - strlen($str);
            $str .= str_repeat($speet, $nums);
        }
        $str .= mt_rand(100000, 999999);
        return $str;
    }
}
//通过身份证号 判断性别
if (!function_exists('getIdentitySex')) {
    function getIdentitySex($identity)
    {
        if (strlen($identity) < 18) {
            return false;
        }
        $res = substr($identity, 16, 1);
        if ($res % 2 == 0) {
            return 1;
        }
        return 0;
    }
}
// 通过 身份证号 判断年纪
if (!function_exists('getIdentityAge')) {
    function getIdentityAge($identity)
    {
        if (strlen($identity) < 18) {
            return false;
        }
        $res = substr($identity, 6, 4);
        $time = date('Y');

        return ($time - $res);
    }
}
if (!function_exists('array_only')) {
    /**
     * Get a subset of the items from the given array.
     *
     * @param array $array
     * @param array|string $keys
     * @return array
     */
    function array_only($array, $keys)
    {
        return Arr::only($array, $keys);
    }
}
if (!function_exists('array_get')) {
    function array_get($array, $key, $default = null)
    {
        if (is_null($key)) {
            return $array;
        }

        if (isset($array[$key])) {
            return $array[$key];
        }

        foreach (explode('.', $key) as $segment) {
            if (!is_array($array) || !array_key_exists($segment, $array)) {
                return value($default);
            }

            $array = $array[$segment];
        }
        return $array;
    }
}
if (!function_exists('jsonEncodeMsg')) {
    function jsonEncodeMsg($value)
    {
        return json_encode($value, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    }
}
if (!function_exists('getMillisecond')) {
    function getMillisecond()
    {
        list($t1, $t2) = explode(' ', microtime());

        return (float)sprintf('%.0f', (floatval($t1) + floatval($t2)) * 1000);
    }
}
if (!function_exists('imgToBase64')) {
    function imgToBase64($img_file)
    {


        $img_base64 = '';

        if (file_exists($img_file)) {

            $app_img_file = $img_file; // 图片路径

            $img_info = getimagesize($app_img_file); // 取得图片的大小，类型等


            //echo '<pre>' . print_r($img_info, true) . '</pre><br>';

            $fp = fopen($app_img_file, "r"); // 图片是否可读权限


            if ($fp) {

                $filesize = filesize($app_img_file);

                $content = fread($fp, $filesize);

                $file_content = (base64_encode($content)); // base64编码

                switch ($img_info[2]) {           //判读图片类型

                    case 1:
                        $img_type = "gif";

                        break;

                    case 2:
                        $img_type = "jpg";

                        break;

                    case 3:
                        $img_type = "png";

                        break;

                }


                $img_base64 = 'data:image/' . $img_type . ';base64,' . $file_content;//合成图片的base64编码


            }

            fclose($fp);

        }


        return $img_base64; //返回图片的base64

    }
}
if (!function_exists('base64ToImg')) {
    function base64ToImg($base64_string)
    {
        $base64_string = explode(',', $base64_string); //截取data:image/png;base64, 这个逗号后的字符
        if (empty($base64_string[1])) {
            return '';
        }
        $data = base64_decode($base64_string[1]);
        return $data;
    }
}
if(!function_exists('lianghaotype')){
    function lianghaotype($phone){
        $type = '';
        // AABB
        // $pattern  = '/(\d)\1\1(\d)\2\2/';
        $pattern  = '#(\d)\1(\d)((?!\1)\2)#';
        if (preg_match($pattern, $phone)) {
            if(!empty($type)){
                $type .=',';
            }
            $type .= 'AABB';
        }
        // ABAB
        $pattern  = '#(\d)(\d)\1((?!\1)\2)#';
        if (preg_match($pattern, $phone)) {
            if(!empty($type)){
                $type .=',';
            }
            $type .= 'ABAB';
        }
        // ABC
        $pattern  = '/(?:(?:0(?=1)|1(?=2)|2(?=3)|3(?=4)|4(?=5)|5(?=6)|6(?=7)|7(?=8)|8(?=9)){2}|(?:9(?=8)|8(?=7)|7(?=6)|6(?=5)|5(?=4)|4(?=3)|3(?=2)|2(?=1)|1(?=0)){2})\d/';
        
        if (preg_match($pattern, $phone)) {
            if(!empty($type)){
                $type .=',';
            }
            $type .= 'ABC';
        }
        // ABCD
        $pattern  = '/(?:(?:0(?=1)|1(?=2)|2(?=3)|3(?=4)|4(?=5)|5(?=6)|6(?=7)|7(?=8)|8(?=9)){3}|(?:9(?=8)|8(?=7)|7(?=6)|6(?=5)|5(?=4)|4(?=3)|3(?=2)|2(?=1)|1(?=0)){3})\d/';
        if (preg_match($pattern, $phone)) {
            if(!empty($type)){
                $type .=',';
            }
            $type .= 'ABCD';
        }
        // ABCDE
        $pattern  = '/(?:(?:0(?=1)|1(?=2)|2(?=3)|3(?=4)|4(?=5)|5(?=6)|6(?=7)|7(?=8)|8(?=9)){4}|(?:9(?=8)|8(?=7)|7(?=6)|6(?=5)|5(?=4)|4(?=3)|3(?=2)|2(?=1)|1(?=0)){4})\d/';
        if (preg_match($pattern, $phone)) {
            if(!empty($type)){
                $type .=',';
            }
            $type .= 'ABCDE';
        }
         // AA
         $pattern  = '/(\d)\1{1}/';
         if (preg_match($pattern, $phone)) {
             if(!empty($type)){
                 $type .=',';
             }
             $type .= 'AA';
         }
         // AAA
         $pattern  = '/(\d)\1{2}/';
         if (preg_match($pattern, $phone)) {
             if(!empty($type)){
                 $type .=',';
             }
             $type .= 'AAA';
         }
         // AAAA
         $pattern  = '/(\d)\1{3}/';
         if (preg_match($pattern, $phone)) {
             if(!empty($type)){
                 $type .=',';
             }
             $type .= 'AAAA';
         }
         // AAAAA
         $pattern  = '/(\d)\1{4}/';
         if (preg_match($pattern, $phone)) {
             if(!empty($type)){
                 $type .=',';
             }
             $type .= 'AAAAA';
         }
        return $type;
    }
}
